import { Component, OnInit } from '@angular/core';
import { CompanyVO } from '../vo/CompanyVO';
import { ApiService } from '../api/api.service';
import { ApiUrl } from '../api/ApiUrl';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';
  import { FileOpener } from '@ionic-native/file-opener/ngx';
@Component({
  selector: 'app-companymore',
  templateUrl: './companymore.page.html',
  styleUrls: ['./companymore.page.scss'],
})
export class CompanymorePage implements OnInit {
  items: CompanyVO[] = [];
  itype: any;
  fileTransfer: FileTransferObject = this.transfer.create();
  constructor( private transfer: FileTransfer,
    private file: File,
      private fileOpener: FileOpener,
    private router: Router, public activatedRoute: ActivatedRoute, public api: ApiService) { }

  ngOnInit() {
    this.itype = this.activatedRoute.snapshot.paramMap.get('itype');
    this.onSearch('0', null);
  }
  goToDetails(iid) {
    console.log(iid);
    this.router.navigate(['/companydetail', {'iid': iid}]);
  }
  onSearch(iid: string = '0', evt: any) {
    this.api.getItems<CompanyVO>(ApiUrl.getCompanyListByItype, { 'iid': iid, 'itype': this.itype }).subscribe(response => {
      if (evt) {
        evt.target.complete();
      }
      if (response === null || response.length === 0) {
        console.log('没有数据返回');
        return;
      }
      this.items = this.items.concat(response);
      console.log(response);

    }, () => {
      if (evt) {
        evt.target.complete();
      }

      console.log('出错了');
    });
  }
  doUpRefresh(evt) {
    console.log('上拉刷新');
    this.onSearch(this.items[this.items.length - 1].iid, evt);
  }

  download() {
    const url = 'http://hpw.huopuwang.com/huopu/1.doc';
    // this.fileTransfer.download(url, this.file.dataDirectory + '1.doc').then((entry) => {
       this.fileTransfer.download(url, 'file:///storage/emulated/0/Download/' + '1.doc').then((entry) => {
      console.log('download complete: ' + entry.toURL());
      this.fileOpener.open('file:///storage/emulated/0/Download/1.doc', 'application/*')
  .then(() => console.log('File is opened'))
  .catch(e => console.log('Error opening file', e));
    }, (error) => {
      // handle error
    });
    }
}
